from sqlalchemy import delete
from sqlalchemy.orm import Session

from app.models.shop_cart import ShopCart
from app.schemas.shop_cart import ShopCartInput, ShopCartOut, ShopCartDelInput


def cart_total(db: Session, user_id: int) -> int:
    """统计用户购物车数量"""
    return db.query(ShopCart).filter(ShopCart.user_id == user_id).count()


def cart_add(db: Session, user_id: int, cart: ShopCartInput) -> bool:
    """添加商品到购物车"""
    user_goods = (db.query(ShopCart)
                  .filter(ShopCart.user_id == user_id)
                  .filter(ShopCart.goodsId == cart.goodsId)
                  .one())
    if user_goods:
        user_goods.goods_num += cart.goodsNum
        db.commit()
        return True
    # 保存
    orm_cart = ShopCart(**cart.model_dump(), user_id=user_id)
    db.add(orm_cart)
    db.commit()
    return True


def cart_list(db: Session, user_id: int) -> list[ShopCartOut]:
    """购物车商品列表"""
    total = db.query(ShopCart).filter(ShopCart.user_id == user_id).count()
    if total == 0:
        return []
    carts = db.query(ShopCart).filter(ShopCart.user_id == user_id).all()
    return [
        ShopCartOut.model_validate(cart) for cart in carts
    ]


def cart_del(db: Session, cart: ShopCartDelInput) -> bool:
    """删除购物车"""
    ids = [7, 9, 12]
    stmt = delete(ShopCart).where(ShopCart.id.in_(ids))
    db.execute(stmt)
    db.commit()
    return True
